<template>
  <!-- ASN单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="70%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[5px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="8">
              <el-form-item label="QAD订单编号" prop="orderNo">
                <el-select
                  v-if="!props.isReadonly"
                  :disabled="props.data.id"
                  @change="orderChange"
                  v-model="formData.orderNo"
                  placeholder="请输入订单编号"
                  filterable
                >
                  <el-option
                    v-for="item in orderList"
                    :key="item.xxqadPodUid"
                    :label="item.xxqadPodNbr"
                    :value="item.xxqadPodNbr"
                  />
                </el-select>
                <span v-else>{{ formData.orderNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工厂" prop="plantId" required>
                <el-select
                  v-if="!props.isReadonly"
                  @change="plantChange"
                  v-model="formData.plantId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in plants"
                    :key="item.id"
                    :label="item.organizationName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else
                  >{{ formData.plantName }} ({{ formData.plantCode }})</span
                >
              </el-form-item></el-col
            >
            <el-col :span="8">
              <el-form-item label="送货单号" prop="asnCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.asnCode"
                  placeholder="请输入送货单号"
                  clearable
                  disabled
                />
                <span v-else>{{ formData.asnCode }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="供应商" prop="partnerCode" required>
                <el-select
                  v-if="!props.isReadonly"
                  @change="partnerChange"
                  v-model="formData.partnerCode"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in partners"
                    :key="item.id"
                    :label="item.partnerCode + '-' + item.partnerName"
                    :value="item.partnerCode"
                  />
                </el-select>
                <span v-else
                  >{{ formData.partnerCode }} - {{ formData.partnerName }}</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运单号" prop="trackingNumber">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.trackingNumber"
                  placeholder="请输入运单号"
                  clearable
                />
                <span v-else>{{ formData.trackingNumber }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="承运人" prop="carrier">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.carrier"
                  placeholder="请输入承运人"
                  clearable
                />
                <span v-else>{{ formData.carrier }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="到货日期" prop="arriveDate">
                <template v-if="!props.isReadonly">
                  <el-date-picker
                    v-model="formData.arriveDate"
                    type="date"
                    placeholder="请选择到货日期"
                    style="width: 192px"
                    clearable
                  />
                </template>
                <template v-else>
                  <span>{{ formData.arriveDate }}</span>
                </template>
              </el-form-item></el-col
            >
            <el-col :span="8">
              <el-form-item label="生产批次" prop="supplyBatch">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.supplyBatch"
                  placeholder="生产批次"
                  @change="supplyChange"
                  clearable
                  maxlength="10"
                  :disabled="!formData.orderNo"
                />
                <span v-else>{{ formData.supplyBatch }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8"
              ><el-form-item label="备注" prop="remarks">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  type="textarea"
                  placeholder="请输入备注"
                  clearable
                  style="width: 100%; box-sizing: border-box"
                />
                <span
                  v-else
                  style="
                    display: block;
                    white-space: pre-wrap;
                    word-break: break-all;
                    width: 100%;
                    box-sizing: border-box;
                  "
                >
                  {{ formData.remarks }}
                </span>
              </el-form-item></el-col
            >
            <el-col :span="8">
              <el-form-item
                v-if="props.isReadonly == false"
                label="是否质检"
                prop="isCheck"
              >
                <el-select
                  v-model="formData.isCheck"
                  placeholder="请选择是否质检"
                  @change="isCheckChange"
                  :disabled="!formData.orderNo"
                >
                  <el-option
                    v-for="item in useDictionary('YesNo')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> </el-form-item
            ></el-col>
          </el-row>
        </div>
        <h4 class="mb-[5px] mt-[20px]">详细数据</h4>
        <el-tabs v-model="defaultTabValue" type="border-card">
          <el-tab-pane label="明细" :name="1">
            <el-card shadow="never" class="table-container">
              <template #header>
                <el-button
                  v-show="!props.isReadonly || !formData.id"
                  type="success"
                  plain
                  @click="handleAdd"
                >
                  <i-ep-plus />
                  新增</el-button
                >
              </template>
              <div class="formTable">
                <el-table
                  :data="formData.details"
                  style="width: 100%"
                  max-height="150"
                  :key="Math.random"
                  border
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    align="center"
                    width="100"
                  />

                  <el-table-column
                    label="存货编码"
                    props="materialCode"
                    min-width="150"
                  >
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.materialCode'"
                        :rules="rules.sonmaterialCode"
                        label-width="0"
                      >
                        <el-select
                          v-if="!props.isReadonly"
                          @change="() => materialChange(row)"
                          v-model="row.materialCode"
                          placeholder="请选择存货编码"
                          clearable
                        >
                          <el-option
                            v-for="item in materials"
                            :key="item.id"
                            :label="item.materialCode + '-' + item.materialName"
                            :value="item.materialCode"
                          />
                        </el-select>
                        <span v-else
                          >{{ row.materialCode }} - {{ row.materialName }}</span
                        >
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="生产批次"
                    props="supplyBatch"
                    min-width="160"
                  >
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.supplyBatch'"
                        :rules="rules.sonsupplyBatch"
                        label-width="0"
                      >
                        <el-input
                          v-if="!props.isReadonly"
                          v-model="row.supplyBatch"
                          placeholder="请输入生产批次"
                          clearable
                          maxlength="10"
                        />
                        <span v-else>{{ row.supplyBatch }}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="是否质检"
                    props="isCheck"
                    min-width="160"
                  >
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.isCheck'"
                        label-width="0"
                      >
                        <el-select
                          v-if="!props.isReadonly"
                          v-model="row.isCheck"
                          placeholder="请选择是否质检"
                          :disabled="!props.isReadonly"
                        >
                          <el-option
                            v-for="item in useDictionary('YesNo')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                        <span v-else>{{
                          row.isCheck === "1"
                            ? "是"
                            : row.isCheck === "0"
                            ? "否"
                            : ""
                        }}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="数量"
                    props="quantity"
                    min-width="170"
                  >
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.quantity'"
                        :rules="rules.sonquantity"
                        label-width="0"
                      >
                        <el-input-number
                          v-if="!props.isReadonly"
                          v-model="row.quantity"
                          placeholder="请输入数量"
                          clearable
                          :min="1"
                        />
                        <span v-else>{{ row.quantity }}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="数量单位"
                    props="unitCode"
                    min-width="150"
                  >
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.unitCode'"
                        :rules="rules.sonunitCode"
                        label-width="0"
                      >
                        <el-select
                          v-if="!props.isReadonly"
                          v-model="row.unitCode"
                          placeholder="请输入数量单位"
                          clearable
                        >
                          <el-option
                            v-for="item in dictionaryStore.filterDictList(
                              'MeasurementUnit'
                            )"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                        <span v-else>{{
                          useDictionary("MeasurementUnit", row.unitCode)
                        }}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" props="remarks" min-width="150">
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.remarks'"
                        label-width="0"
                      >
                        <el-input
                          v-if="!props.isReadonly"
                          v-model="row.remarks"
                          placeholder="请输入备注"
                          clearable
                        />
                        <span v-else>{{ row.remarks }}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="100"
                    v-if="!props.isReadonly"
                  >
                    <template #default="scope">
                      <el-button
                        :disabled="formData.details.length < 2"
                        type="danger"
                        link
                        @click.stop="handleDelete(scope.$index)"
                        ><i-ep-delete />
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>
          <el-tab-pane
            label="合计"
            :name="2"
            v-if="formData.materialSum.length"
          >
            <el-card shadow="never" class="table-container">
              <div class="formTable">
                <el-table
                  :data="formData.materialSum"
                  style="width: 100%"
                  :key="Math.random"
                  border
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    align="center"
                    width="100"
                  />

                  <el-table-column
                    label="物料"
                    props="materialCode"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span
                        >{{ row.materialCode }} - {{ row.materialName }}</span
                      >
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="批次"
                    props="supplyBatch"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.supplyBatch }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="总数"
                    props="quantity"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.quantity }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="总箱数"
                    props="counts"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.counts }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useDictionary } from "@/utils/useTable";
import { string } from "fast-glob/out/utils";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMASNPARTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let plants = ref([]);
let materials = ref([]);
let partners = ref([]);
let defaultTabValue = ref(1);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    console.log("newVal", newVal);
    visibleDialog.value = newVal;
    partners.value = [];
    materials.value = [];
    getPlants();
    if (newVal === true) {
      setTimeout(() => {
        formRef.value.clearValidate();
      }, 50);
    }
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  orderNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  asnCode: getHourMinuteSecond(),
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  asnDate: "",
  arriveDate: "",
  modeTransport: "",
  trackingNumber: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  carrier: "",
  shippingContactPerson: "",
  shippingContactPhone: "",
  plateNumber: "",
  shipmentStatus: "3",
  remarks: "",
  unitNumber: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  supplyBatch: getCurrentDate(),
  supplyCode: "",
  isCheck: "1",
  details: [
    {
      id: "",
      asnId: "",
      materialId: "",
      materialCode: "",
      materialName: "",
      supplyBatch: getCurrentDate(),
      supplyCode: "",
      isCheck: "1",
      quantity: 1,
      unitCode: "",
      remarks: "",
      unitNumber: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
    },
  ],
  materialSum: [
    {
      supplyBatch: "",
      materialId: "",
      materialCode: "",
      materialName: "",
      quantity: "",
      unitCode: "",
    },
  ],
});
// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + month + day;
}
/** rules规则 */
const rules = reactive({
  asnCode: [{ required: true, message: "请输入送货单号", trigger: "blur" }],
  orderNo: [{ required: true, message: "请输入订单编号", trigger: "blur" }],
  organizationId: [
    { required: true, message: "请输入公司ID;基本信息", trigger: "blur" },
  ],
  organizationCode: [
    { required: true, message: "请输入公司代码;基本信息", trigger: "blur" },
  ],
  organizationName: [
    { required: true, message: "请输入公司名称;基本信息", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  plantCode: [{ required: true, message: "请输入工厂代码", trigger: "blur" }],
  plantName: [{ required: true, message: "请输入工厂名称", trigger: "blur" }],
  partnerId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  partnerCode: [{ required: true, message: "请选择供应商", trigger: "change" }],
  partnerName: [
    { required: true, message: "请输入供应商名称", trigger: "blur" },
  ],
  asnDate: [{ required: true, message: "请输入送货日期", trigger: "blur" }],
  arriveDate: [
    { required: true, message: "请输入预计到货日期", trigger: "blur" },
  ],

  shipmentStatus: [
    { required: true, message: "请输入发货状态", trigger: "change" },
  ],

  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  createdUserId: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  createdUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  lastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  lastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  deleted: [{ required: true, message: "请输入是否删除", trigger: "blur" }],
  sonasnId: [{ required: true, message: "请输入ASN单ID", trigger: "blur" }],
  sonorderId: [{ required: true, message: "请输入订单ID", trigger: "blur" }],
  sonmaterialDetailId: [
    { required: true, message: "请输入ASN关联的物料信息表ID", trigger: "blur" },
  ],
  sonunitBarcode: [
    { required: true, message: "请输入箱标签号", trigger: "blur" },
  ],
  sonmaterialId: [{ required: true, message: "请输入物料id", trigger: "blur" }],
  sonmaterialCode: [
    { required: true, message: "请选择物料", trigger: "change" },
  ],
  sonmaterialName: [
    { required: true, message: "请输入物料名称", trigger: "blur" },
  ],
  sonsupplyBatch: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
    { pattern: /^\d+$/, message: "请输入数字", trigger: "change" },
    // { validator: validateEndTime, trigger: "change" },
  ],
  sonquantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  sonisreceive: [
    { required: true, message: "请输入是否收货", trigger: "blur" },
  ],
  sonunitCode: [
    { required: true, message: "请输入数量单位", trigger: "change" },
  ],

  soncreateTime: [
    { required: true, message: "请输入创建时间", trigger: "blur" },
  ],
  soncreatedUserId: [
    { required: true, message: "请输入创建人", trigger: "blur" },
  ],
  soncreatedUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  sonlastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  sonlastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  sonlastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  sondeleted: [{ required: true, message: "请输入是否删除", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  formRef.value.clearValidate();
};
// 获取当前日期yyyymmdd时分秒
function getHourMinuteSecond() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  const day = ("0" + now.getDate()).slice(-2);
  const hours = ("0" + now.getHours()).slice(-2);
  const minutes = ("0" + now.getMinutes()).slice(-2);
  const seconds = ("0" + now.getSeconds()).slice(-2);
  return year + month + day + hours + minutes + seconds;
}
const details = {
  id: "",
  asnId: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  supplyBatch: getCurrentDate(),
  supplyCode: "",
  isCheck: "1",
  quantity: 1,
  unitCode: "",
  remarks: "",
  unitNumber: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

// /** 添加行 */
// const handleAdd = () => {
//   let sondata = {}; // 创建一个空对象
//   console.log(sondata);
//   sondata.quantity = 1;
//   formData.details.push(sondata);
// };
/** 添加行 */
const handleAdd = () => {
  // 创建一个新行对象，并将需要的属性复制
  let newRow = {
    id: "", // 根据需要，可以重置 ID
    supplyBatch: formData.supplyBatch || "", // 复制上一个行的生产批次
    supplyCode: formData.supplyCode || "", // 复制上一个行的生产批次
    isCheck: formData.isCheck || "", // 复制上一个行的生产批次
    quantity: 1,
    // 其他属性可以根据需要添加或重置
  };

  formData.details.push(newRow); // 将新行对象推入 details 数组
};
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    console.log("newVal", formData.id);
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
      formData.isCheck = String(formData.isCheck);
      console.log("formData", formData.materialSum.length);
      getPlants();
      getOrganization();
      getPartner(formData.partnerCode);
      getMaterials(formData.orderNo);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  defaultTabValue.value = 1;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.orderNo = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.asnCode = getHourMinuteSecond();
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.asnDate = "";
  formData.arriveDate = "";
  formData.modeTransport = "";
  formData.trackingNumber = "";
  formData.storageLocationId = "";
  formData.storageLocationCode = "";
  formData.storageLocationName = "";
  formData.carrier = "";
  formData.shippingContactPerson = "";
  formData.shippingContactPhone = "";
  formData.plateNumber = "";
  formData.shipmentStatus = "3";
  formData.remarks = "";
  formData.unitNumber = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.supplyBatch = getCurrentDate();
  formData.supplyCode = "";
  formData.isCheck = "1";
  formData.materialSum = [];
}

const loading = ref(false);
async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
  formData.plantId = data.data[0].id;
  formData.plantCode = data.data[0].organizationCode;
  formData.plantName = data.data[0].organizationName;
  formData.organizationId = data.data[0].parentId;
  getOrganization();
}
async function getPartner(code: string) {
  const data = await request({
    url: `/mdm/mdmpartner/queryByPartnerCode?partnerCode=${code}`,
    method: "get",
  });
  if (data.data.length > 0) {
    partners.value = data.data;
    formData.partnerId = data.data[0].id;
    formData.partnerName = data.data[0].partnerName;
  } else {
    formData.partnerCode = "";
  }
}
async function getOrganization() {
  const data = await request({
    url: `/system/sysOrganization/get/${formData.organizationId}`,
    method: "post",
    data: {},
  });
  formData.organizationCode = data.data.organizationCode;
  formData.organizationName = data.data.organizationName;
}

function partnerChange() {
  var partner = partners.value.find((item) => {
    return item.partnerCode === formData.partnerCode;
  });

  formData.partnerId = partner.id;
  // formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
  // getMaterials();
}

function materialChange(row) {
  if (row && row.materialCode && materials.value) {
    var material = materials.value.find(
      (item) => item.materialCode === row.materialCode
    );
    if (material) {
      row.materialId = material.id; // 更新当前行的materialId
      row.materialName = material.materialName; // 更新当前行的materialName
      row.unitCode = material.unit;
    }
  }
}
function plantChange() {
  var plant = plants.value.find((item) => {
    return item.id === formData.plantId;
  });

  formData.plantCode = plant.organizationCode;
  formData.plantName = plant.organizationName;
  formData.organizationId = plant.parentId;
  // formData.partnerId = "";
  // formData.partnerCode = "";
  // formData.partnerName = "";
  // formData.details = [];

  getOrganization();
  // getPartners();
}
function supplyChange() {
  formData.details.forEach((detail) => {
    detail.supplyBatch = formData.supplyBatch; // 设置为当前的生产批次
  });
}

function isCheckChange() {
  formData.details.forEach((detail) => {
    detail.isCheck = formData.isCheck; // 设置为当前是否质检
  });
}
/** ASN单（平面级）保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    // if (formData.asnDate > formData.arriveDate) {
    //   ElMessage.error(`送货时间应小于预计到货时间`);
    //   return;
    // }
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/srm/srmasnpart/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
function validateEndTime(rule, value, callback) {
  const dateFormat = /^\d{8}$/; // 正则表达式，验证是否为八位数字字符串
  if (!dateFormat.test(value)) {
    callback(new Error("不符合 (yyyyMMdd)格式"));
  } else {
    callback();
  }
}
async function getdetails() {
  let sondetails = await request({
    url: "/srm/srmasnpart/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  formData.details.forEach((element) => {
    element.isCheck = String(element.isCheck);
  });
}
//采购订单
const orderList = ref([]);
async function getPurchaseOrder() {
  let sondetails = await request({
    url: "/wms/xxqadpoddet/getQADList",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  orderList.value = sondetails.data;
}

function orderChange() {
  var order = orderList.value.find((item) => {
    return item.xxqadPodNbr === formData.orderNo;
  });
  partners.value = [];
  materials.value = [];
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.orderNo = order.xxqadPodNbr;
  formData.partnerCode = order.xxqadPodVend;
  getPartner(order.xxqadPodVend);
  getMaterials(order.xxqadPodNbr);
  formData.isCheck = "1";
  formData.supplyBatch = getCurrentDate();
}
async function getMaterials(code: string) {
  const data = await request({
    url: `/wms/xxqadpoddet/getMaterials?xxqadPodNbr=${code}`,
    method: "get",
  });
  materials.value = data.data;
}
onMounted(() => {
  getPurchaseOrder();
  formData.materialSum = [];
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    font-size: 16px;
  }
}

:deep(.el-form-item) {
  margin: 0;
  padding: 8px 0;
}
</style>
